import {
  Text,
  View,
  StyleSheet,
  TextInput,
  Image,
  TouchableOpacity,
  Alert,
  Platform,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useState, useEffect } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { useRouter } from "expo-router"; // 引入 useRouter
import useAppStateChange from "@/hooks/useAppStateChange";
import useInputWithDone from "@/hooks/useInputWithDone";
import useCaptchaCountdown from "@/hooks/useCaptchaCountdown";
import { registerMemberFnApi } from "./api";
import { ToastAPI } from "@/components/Toast";
import HeaderWithLanguageSelector from "@/components/HeaderWithLanguageSelector";
import { getRegisterMemberVerifyFnAPi } from "./api";
import { useTranslation } from "react-i18next";

export default function Register() {
  const { t } = useTranslation();

  const router = useRouter(); // 获取路由对象
  const appState = useAppStateChange();
  const { countdown, isDisabled, handleGetCaptcha, verifyId } =
    useCaptchaCountdown(getRegisterMemberVerifyFnAPi) as any;
  const [username, setUsername, handleUsernameDone] = useInputWithDone() as any;
  const [phoneOrEmail, setPhoneOrEmail, handlePhoneOrEmailDone] =
    useInputWithDone() as any;
  const [password, setPassword, handlePasswordDone] = useInputWithDone() as any;
  const [paymentPassword, setPaymentPassword, handlePaymentPasswordDone] =
    useInputWithDone() as any;
  const [captChaCode, setCaptChaCode, handleCaptChaCodeDone] =
    useInputWithDone() as any;

  // 验证手机号或邮箱号格式
  const [phoneOrEmailError, setPhoneOrEmailError] = useState<string | null>(
    null
  );
  const validatePhoneOrEmail = (input: string) => {
    setPhoneOrEmail(input);
    const phoneRegex = /^1[3-9]\d{9}$/;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const reslt = phoneRegex.test(input) || emailRegex.test(input);
    setPhoneOrEmailError(reslt ? null : t("register.error.phoneOrEmail"));
  };
  //验证用户昵称
  const [userNameError, setUserNameError] = useState<string | null>(null);
  const validateUserName = (input: string) => {
    setUsername(input);
    const regex = /^[\dA-Za-z\u4e00-\u9fa5-_]{1,16}$/;
    setUserNameError(regex.test(input) ? null : t("register.error.username"));
  };

  // 验证密码
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const validatePasswordError = (input: string) => {
    setPassword(input);
    const passwordRegex =
      /^(?=(.*[a-z]))(?=(.*[A-Z]))(?=(.*\d))(?=[\x21-\x7e]{8,16}$).*/;

    setPasswordError(
      passwordRegex.test(input) ? null : t("register.error.password")
    );
  };

  //验证支付密码
  const [paymentPasswordError, setPaymentPasswordError] = useState<
    string | null
  >(null);
  const validatePaymentPasswordError = (input: string) => {
    setPaymentPassword(input);
    const regex = /^\d{6}$/;
    setPaymentPasswordError(
      regex.test(input) ? null : t("register.error.paymentPassword")
    );
  };

  // 处理注册逻辑
  const handleRegisteredFn = async () => {
    if (
      !username ||
      !phoneOrEmail ||
      !password ||
      !paymentPassword ||
      !captChaCode
    ) {
      ToastAPI.warning(t("register.toast.warning.incomplete"));
      return;
    }
    if (
      userNameError ||
      phoneOrEmailError ||
      passwordError ||
      paymentPasswordError
    ) {
      ToastAPI.warning(t("register.toast.warning.invalid"));
      return;
    }
    ToastAPI.loading(t("register.toast.loading.registering"), "center", -1);
    try {
      const res: any = await registerMemberFnApi({
        nickName: username,
        payload: phoneOrEmail,
        loginPassword: password,
        paymentPassword: paymentPassword,
        verifyCode: captChaCode,
        verifyId,
      });
      ToastAPI.close();
      if (res.code === 0) {
        Alert.alert(
          t("register.alert.registerSuccess"),
          t("register.alert.registerSuccessMessage"),
          [
            {
              text: t("register.button.cancel"),
              style: "cancel",
            },
            {
              text: t("register.button.login"),
              onPress: () => {
                router.back();
              },
            },
          ]
        );
      } else {
        ToastAPI.error(
          res?.errMsg || t("register.toast.error.registerFailed")
        );
      }
    } catch (error) {
      // 捕获错误并关闭加载提示
      ToastAPI.close();
      ToastAPI.error(
        JSON.stringify(error) || t("register.toast.error.requestError")
      );
    }
  };

  return (
    <PageContainer>
      <View className="flex-1" style={styles.main}>
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <Image
              source={require("@/assets/images/logo-icon.png")}
              className="w-[68px] h-[18px]"
            />
          </View>
          <HeaderWithLanguageSelector />
        </View>
        {/* 使用 KeyboardAwareScrollView 包裹内容 */}
        <KeyboardAwareScrollView
          contentContainerStyle={styles.scrollContainer}
          extraHeight={100}
        >
          <View>
            <Text style={styles.title}>{t("login.title")}</Text>
            <Text className="text-[#D7D7D7] text-[16px] mt-[15px]">
              {t("register.tip")}
            </Text>
          </View>
          <View>
            <Text className="mt-[46px] text-[#D7D7D7] text-[16px]">
              {t("register.input.nickname")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handleUsernameDone}
              blurOnSubmit={true}
              placeholder={t("register.input.placeholder.nickname")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={username}
              onChangeText={validateUserName}
            />
            {userNameError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {userNameError}
              </Text>
            )}
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("register.input.phoneOrEmail")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handlePhoneOrEmailDone}
              blurOnSubmit={true}
              placeholder={t("register.input.placeholder.phoneOrEmail")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={phoneOrEmail}
              onChangeText={validatePhoneOrEmail}
            />
            {phoneOrEmailError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {phoneOrEmailError}
              </Text>
            )}
          </View>

          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("register.input.captcha")}
            </Text>
            <View className="flex-row justify-between items-center bg-[#25262A] rounded-[10px] h-[50px] mt-[15px] px-[12px]">
              <TextInput
                style={[{ fontSize: 16, color: "#fff", flex: 1 }]}
                placeholder={t("register.input.placeholder.captcha")}
                placeholderTextColor={"rgba(255,255,255,0.3)"}
                value={captChaCode}
                onChangeText={setCaptChaCode}
                returnKeyType="done"
                onSubmitEditing={handleCaptChaCodeDone}
                blurOnSubmit={true}
                maxLength={6}
              />
              <TouchableOpacity
                onPress={() => handleGetCaptcha(phoneOrEmail)}
                disabled={isDisabled}
              >
                <Text className="text-[#6FC2FA] w-[80px]">
                  {countdown > 0
                    ? `${countdown}s后重试`
                    : t("register.button.getCaptcha")}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("register.input.password")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              placeholder={t("register.input.placeholder.password")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={password}
              returnKeyType="done"
              onSubmitEditing={handlePasswordDone}
              blurOnSubmit={true}
              secureTextEntry
              onChangeText={validatePasswordError}
            />
            {passwordError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {passwordError}
              </Text>
            )}
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("register.input.paymentPassword")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handlePaymentPasswordDone}
              blurOnSubmit={true}
              placeholder={t("register.input.placeholder.paymentPassword")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={paymentPassword}
              secureTextEntry
              keyboardType="numeric"
              maxLength={6}
              onChangeText={validatePaymentPasswordError}
            />
            {paymentPasswordError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {paymentPasswordError}
              </Text>
            )}
          </View>

          <TouchableOpacity onPress={handleRegisteredFn}>
            <LinearGradient
              style={styles.loginBtn}
              colors={["#3D7FFF", "#6FC2FA"]}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Text className="text-[#fff] text-[16px]">
                {t("register.button.register")}
              </Text>
            </LinearGradient>
          </TouchableOpacity>
        </KeyboardAwareScrollView>
      </View>
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  scrollContainer: {
    flexGrow: 1, // 使内容能够伸展
  },
  main: {
    paddingLeft: 13,
    paddingRight: 13,
  },

  title: {
    fontSize: 24,
    color: "#fff",
    fontWeight: 600,
    paddingTop: 53,
  },
  input: {
    height: 50,
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
  },
  loginBtn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
});
